package net.esj.basic.core.view.interceptor;

import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;

import net.esj.basic.core.utils.RegexUtils;
import net.esj.basic.core.view.action.SensWordsActionHandler;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SensitiveWordInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1180378696759196300L;

	public static final String SENS_WORDS_ERROR = "sensWordsError";
	
	private Pattern pattern = null;

	private Properties sensWords;
	
	@Override
	public String intercept(ActionInvocation inv) throws Exception {
		if(inv.getAction() instanceof SensWordsActionHandler){
			List<String> groups = Collections.EMPTY_LIST;
			if(pattern!=null){
				groups = RegexUtils.groups(pattern, inv.getAction());
			}
			if(groups.isEmpty()){
				return inv.invoke();
			}else{
				return errorHandler(inv,groups);
			}
		}else{
			return inv.invoke();
		}
	}

	
	
	@PostConstruct
	public void afterPropertiesSet() {
		StringBuffer patternBuf = new StringBuffer("");
		if (sensWords == null) {
			return;
		}
		Enumeration enu = sensWords.propertyNames();
		patternBuf.append("(");
		while (enu.hasMoreElements()) {
			patternBuf.append((String) enu.nextElement() + "|");
		}
		patternBuf.deleteCharAt(patternBuf.length() - 1);
		patternBuf.append(")");
		// unix换成UTF-8
		// pattern = Pattern.compile(new
		// String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));
		// win下换成gb2312
		// pattern = Pattern.compile(new String(patternBuf.toString()
		// .getBytes("ISO-8859-1"), "gb2312"));
		pattern = Pattern.compile(patternBuf.toString());
	}

	public void setSensWords(Properties sensWords) {
		this.sensWords = sensWords;
	}

	/**
	 * if need to rewrite
	 * @param inv
	 * @return
	 */
	protected String errorHandler(ActionInvocation inv,List<String> list){
		return ((SensWordsActionHandler)inv.getAction()).handle(list);
	}
	
}
